package jmotioncapture.testing.framework;

import jmotioncapture.camera.FrameSet;

import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.border.TitledBorder;

/**
 * This class refresh the panel that displaying the frames and points on GUI. If
 * <code>isWait</code> is set to true, the panel will show points accroding to
 * the <code>interval</code>, otherwise, the points will show up at once.
 * 
 * @author Kenneth
 * @since 1.0.0
 */
public class DrawTimer implements Runnable {

	/**
	 * Parent GUI
	 */
	private TestingPanel parent;

	/**
	 * Set to true when need to wait <code>interval</code> between each point,
	 * otherwise set to false.
	 */
	private boolean isWait = false;

	/**
	 * Time for waiting between each point.
	 */
	private long interval;

	/**
	 * Frames object
	 */
	private FrameSet frames;

	/**
	 * 
	 * @param parent
	 * @param isWait
	 */
	public DrawTimer(TestingPanel parent, boolean isWait) {
		this.parent = parent;
		this.interval = parent.interval;
		this.frames = parent.frames;
		this.isWait = isWait;
	}

	/**
	 * Start the thread
	 */
	public void run() {

		if (isWait) {
			for (int i = 0; i < frames.size(); i++) {
				refreshDrawingPanel(frames.framesBetween(0, i, 0));

				try {
					Thread.sleep(this.interval);
				} catch (InterruptedException e) {
					
					e.printStackTrace();
				}
			}
		} else {
			refreshDrawingPanel(frames);
		}
	}

	private void refreshDrawingPanel(FrameSet frames) {
		DrawPanel tempPanel = new DrawPanel(frames,
				this.parent.withLinkedLineCheckBox.isSelected(),
				this.parent.withPointCheckBox.isSelected(),
				this.parent.withLabelCheckBox.isSelected());

		this.parent.panel = tempPanel;
		this.parent.panel.setLayout(null);
		this.parent.panel.setBorder(new TitledBorder(null, "",
				TitledBorder.DEFAULT_JUSTIFICATION,
				TitledBorder.DEFAULT_POSITION, null, null));
		this.parent.panel.setBackground(Color.WHITE);
		this.parent.panel.setBounds(10, 30, 472, 491);
		this.parent.panel.addMouseMotionListener(this.parent);
		this.parent.panel.addMouseListener(new MouseAdapter() {
			public void mouseClicked(final MouseEvent arg0) {
				parent.panel_Click(arg0);
			}
		});
		this.parent.frame.getContentPane().add(this.parent.panel);
		this.parent.panel.repaint();
	}

}
